<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" class="search-form">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item label="配置编码">
                            <el-input v-model="searchForm.configCode" placeholder="请输入配置编码" clearable
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <el-form-item label="配置名称">
                            <el-input v-model="searchForm.configName" placeholder="请输入配置名称" clearable
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <el-form-item label="监控对象">
                            <el-select v-model="searchForm.targetType" placeholder="请选择监控对象" clearable
                                style="width: 100%">
                                <el-option v-for="item in monitoringOptions" :key="item.dictValue"
                                    :label="item.dictLabel" :value="item.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <el-form-item label="刷新模式">
                            <el-select v-model="searchForm.refreshMode" placeholder="请选择刷新模式" clearable
                                style="width: 100%">
                                <el-option label="实时" :value="1" />
                                <el-option label="定时" :value="2" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <el-form-item label="启用状态">
                            <el-select v-model="searchForm.isEnabled" placeholder="请选择状态" clearable style="width: 100%">
                                <el-option label="启用" :value="1" />
                                <el-option label="停用" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <div class="form-actions">
                            <el-button type="primary" @click="handleSearch" :loading="loading">
                                <el-icon class="el-icon--left">
                                    <Search />
                                </el-icon>
                                查询
                            </el-button>
                            <el-button @click="resetSearch">
                                <el-icon class="el-icon--left">
                                    <Refresh />
                                </el-icon>
                                重置
                            </el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 数据表格区域 -->
        <el-card class="table-card mt-2">
            <div class="action-buttons">
                <el-button type="primary" @click="handleAdd">
                    <el-icon class="el-icon--left">
                        <Plus />
                    </el-icon>
                    新增配置
                </el-button>
                <!-- <el-button type="warning" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
                    <el-icon class="el-icon--left">
                        <Delete />
                    </el-icon>
                    批量删除
                </el-button>
                <el-button type="success" @click="handleBatchEnable" :disabled="selectedRows.length === 0">
                    <el-icon class="el-icon--left">
                        <Check />
                    </el-icon>
                    批量启用
                </el-button>
                <el-button type="danger" @click="handleBatchDisable" :disabled="selectedRows.length === 0">
                    <el-icon class="el-icon--left">
                        <Close />
                    </el-icon>
                    批量停用
                </el-button> -->
            </div>

            <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange"
                class="mt-2">
                <el-table-column type="selection" width="55" align="center" />

                <el-table-column prop="id" label="ID" align="center" width="80" />

                <el-table-column prop="configCode" label="配置编码" align="center">
                    <template #default="{ row }">
                        <span>{{ row.configCode || '-' }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="configName" label="配置名称" align="center" show-overflow-tooltip>
                    <template #default="{ row }">
                        <span>{{ row.configName || '-' }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="targetLabel" label="监控对象" align="center">
                    <template #default="{ row }">
                        <span>{{ row.targetLabel || '-' }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="refreshMode" label="刷新模式" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getRefreshModeTag(row.refreshMode)" size="small">
                            {{ getRefreshModeText(row.refreshMode) }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="refreshSeconds" label="刷新间隔" align="center">
                    <template #default="{ row }">
                        <span>{{ formatRefreshSeconds(row.refreshSeconds, row.refreshMode) }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="fontFamily" label="字体" align="center">
                    <template #default="{ row }">
                        <span>{{ row.fontFamily || '默认' }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="isEnabled" label="状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTag(row.isEnabled)" size="small">
                            {{ getStatusText(row.isEnabled) }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="createdAt" label="创建时间" align="center">
                    <template #default="{ row }">
                        <span>{{ formatDateTime(row.createdAt) }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="updatedAt" label="更新时间" align="center">
                    <template #default="{ row }">
                        <span>{{ formatDateTime(row.updatedAt) }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center" width="280">
                    <template #default="{ row }">
                        <el-button type="primary" link size="small" @click="handleView(row)">
                            查看
                        </el-button>
                        <el-button type="warning" link size="small" @click="handleEdit(row)">
                            编辑
                        </el-button>
                        <el-button v-if="row.isEnabled === 1" type="danger" link size="small"
                            @click="handleToggleStatus(row, 0)">
                            停用
                        </el-button>
                        <el-button v-if="row.isEnabled === 0" type="success" link size="small"
                            @click="handleToggleStatus(row, 1)">
                            启用
                        </el-button>
                        <el-button type="danger" link size="small" @click="handleDelete(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :total="pagination.total" :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900px" :before-close="handleCloseDialog">
            <el-form ref="formRef" :model="formData" :rules="formRules">
                <el-tabs v-model="activeTab" type="border-card">
                    <!-- 基本信息 -->
                    <el-tab-pane label="基本信息" name="basic">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="配置编码" prop="configCode">
                                    <el-input v-model="formData.configCode" placeholder="请输入配置编码" style="width: 100%" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="配置名称" prop="configName">
                                    <el-input v-model="formData.configName" placeholder="请输入配置名称" style="width: 100%" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="监控对象类型" prop="targetType">
                                    <el-select v-model="formData.targetType" placeholder="请选择监控对象类型"
                                        style="width: 100%">
                                        <el-option v-for="item in monitoringOptions" :key="item.dictValue"
                                            :label="item.dictLabel" :value="item.dictValue" />
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="监控对象标签">
                                    <el-input v-model="formData.targetLabel" placeholder="请输入监控对象标签"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="刷新模式" prop="refreshMode">
                                    <el-select v-model="formData.refreshMode" placeholder="请选择刷新模式" style="width: 100%">
                                        <el-option label="实时" :value="1" />
                                        <el-option label="定时" :value="2" />
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="刷新间隔" prop="refreshSeconds">
                                    <el-input-number v-model="formData.refreshSeconds" :min="0" :max="3600"
                                        placeholder="刷新间隔秒数" style="width: 100%"
                                        :disabled="formData.refreshMode === 1" />
                                    <div class="form-tip" v-if="formData.refreshMode === 1">实时模式刷新间隔为0</div>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="字体">
                                    <el-select v-model="formData.fontFamily" placeholder="请选择字体" style="width: 100%">
                                        <el-option label="默认字体" value="default" />
                                        <el-option label="微软雅黑" value="Microsoft YaHei" />
                                        <el-option label="宋体" value="SimSun" />
                                        <el-option label="黑体" value="SimHei" />
                                        <el-option label="Arial" value="Arial" />
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="字体颜色">
                                    <el-color-picker v-model="formData.fontColor" show-alpha />
                                    <el-input v-model="formData.fontColor" placeholder="#RRGGBB"
                                        style="width: 120px; margin-left: 10px" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="背景颜色">
                                    <el-color-picker v-model="formData.bgColor" show-alpha />
                                    <el-input v-model="formData.bgColor" placeholder="#RRGGBB"
                                        style="width: 120px; margin-left: 10px" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="启用状态">
                                    <el-switch v-model="formData.isEnabled" :active-value="1" :inactive-value="0"
                                        active-text="启用" inactive-text="停用" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="24">
                                <el-form-item label="备注">
                                    <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-tab-pane>

                    <!-- 表格列配置 -->
                    <el-tab-pane label="表格列配置" name="columns">
                        <div class="config-section">
                            <div class="section-header">
                                <span>列配置列表</span>
                                <el-button type="primary" link @click="addColumn">
                                    <el-icon>
                                        <Plus />
                                    </el-icon>添加列
                                </el-button>
                            </div>
                            <div class="config-list">
                                <div v-for="(column, index) in formData.columnConfigs" :key="index" class="config-item">
                                    <el-row :gutter="20">
                                        <el-col :span="8">
                                            <el-form-item :label="`列${index + 1}字段`">
                                                <el-select v-model="column.fieldCode" placeholder="选择字段"
                                                    style="width: 100%">
                                                    <el-option v-for="field in fieldOptions" :key="field.value"
                                                        :label="field.label" :value="field.value" />
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="8">
                                            <el-form-item label="列名">
                                                <el-input v-model="column.headerText" placeholder="列名" />
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="8">
                                            <el-form-item label="宽度(px)">
                                                <el-input-number v-model="column.widthPx" :min="50" :max="500"
                                                    style="width: 100%" />
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="8">
                                            <el-form-item label="对齐方式">
                                                <el-select v-model="column.align" placeholder="对齐方式"
                                                    style="width: 100%">
                                                    <el-option v-for="align in alignOptions" :key="align.dictValue"
                                                        :label="align.dictLabel" :value="align.dictValue" />
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="3">
                                            <el-form-item label="操作">
                                                <el-button type="danger" link @click="removeColumn(index)"
                                                    :disabled="formData.columnConfigs.length <= 1">
                                                    <el-icon>
                                                        <Delete />
                                                    </el-icon>
                                                </el-button>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>

                    <!-- 筛选条件配置 -->
                    <el-tab-pane label="筛选条件" name="filters">
                        <div class="config-section">
                            <div class="section-header">
                                <span>筛选条件列表</span>
                                <el-button type="primary" link @click="addFilter">
                                    <el-icon>
                                        <Plus />
                                    </el-icon>添加条件
                                </el-button>
                            </div>
                            <div class="config-list">
                                <div v-for="(filter, index) in formData.filterConfigs" :key="index" class="config-item">
                                    <el-row :gutter="20">
                                        <el-col :span="6">
                                            <el-form-item :label="`条件${index + 1}字段`">
                                                <el-select v-model="filter.fieldCode" placeholder="选择字段"
                                                    style="width: 100%">
                                                    <el-option v-for="field in fieldOptions" :key="field.value"
                                                        :label="field.label" :value="field.value" />
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="运算符">
                                                <el-select v-model="filter.operator" placeholder="选择运算符"
                                                    style="width: 100%">
                                                    <el-option v-for="symbol in symbolOptions" :key="symbol.dictValue"
                                                        :label="symbol.dictLabel" :value="symbol.dictValue" />
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="值">
                                                <el-input v-model="filter.valueText" placeholder="输入值" />
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="操作">
                                                <el-button type="danger" link @click="removeFilter(index)"
                                                    :disabled="formData.filterConfigs.length <= 1">
                                                    <el-icon>
                                                        <Delete />
                                                    </el-icon>
                                                </el-button>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>

                    <!-- 预览 -->
                    <el-tab-pane label="预览" name="preview">
                        <div class="preview-section">
                            <div class="preview-header">
                                <h4>表格预览</h4>
                                <div class="preview-actions">
                                    <el-button type="primary" size="small" @click="refreshPreview">
                                        <el-icon>
                                            <Refresh />
                                        </el-icon>刷新预览
                                    </el-button>
                                </div>
                            </div>
                            <div class="preview-table">
                                <el-table :data="previewData" :style="{
                                    fontFamily: formData.fontFamily || 'default',
                                    color: formData.fontColor || '#000000',
                                    backgroundColor: formData.bgColor || '#ffffff'
                                }" border style="width: 100%">
                                    <el-table-column v-for="column in formData.columnConfigs" :key="column.fieldCode"
                                        :prop="column.fieldCode" :label="column.headerText" :align="column.align">
                                        <template #default="{ row }">
                                            <span>{{ row[column.fieldCode] || '-' }}</span>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </el-form>

            <template #footer>
                <el-button @click="handleCloseDialog">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitting">
                    {{ dialogType === 'add' ? '新增' : '保存' }}
                </el-button>
            </template>
        </el-dialog>

        <!-- 查看详情对话框 -->
        <el-dialog v-model="viewDialogVisible" title="配置详情" width="800px" :before-close="handleCloseViewDialog">
            <div v-if="currentDetail">
                <el-descriptions title="基本信息" :column="2" border>
                    <el-descriptions-item label="记录ID">{{ currentDetail.id || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="配置编码">{{ currentDetail.configCode || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="配置名称">{{ currentDetail.configName || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="监控对象类型">{{ currentDetail.targetType || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="监控对象标签">{{ currentDetail.targetLabel || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="刷新模式">
                        <el-tag :type="getRefreshModeTag(currentDetail.refreshMode)" size="small">
                            {{ getRefreshModeText(currentDetail.refreshMode) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="刷新间隔">
                        {{ formatRefreshSeconds(currentDetail.refreshSeconds, currentDetail.refreshMode) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="字体">{{ currentDetail.fontFamily || '默认' }}</el-descriptions-item>
                    <el-descriptions-item label="字体颜色">
                        <span :style="{ color: currentDetail.fontColor }">{{ currentDetail.fontColor || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="背景颜色">
                        <span
                            :style="{ backgroundColor: currentDetail.bgColor, padding: '2px 8px', borderRadius: '4px' }">
                            {{ currentDetail.bgColor || '-' }}
                        </span>
                    </el-descriptions-item>
                    <el-descriptions-item label="状态">
                        <el-tag :type="getStatusTag(currentDetail.isEnabled)" size="small">
                            {{ getStatusText(currentDetail.isEnabled) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="创建时间">{{ formatDateTime(currentDetail.createdAt) || '-'
                        }}</el-descriptions-item>
                    <el-descriptions-item label="更新时间">{{ formatDateTime(currentDetail.updatedAt) || '-'
                        }}</el-descriptions-item>
                    <el-descriptions-item label="备注" :span="2">
                        {{ currentDetail.remark || '无' }}
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions v-if="currentDetail.columnConfigs && currentDetail.columnConfigs.length > 0"
                    title="列配置" :column="1" border class="mt-3">
                    <el-descriptions-item label="列配置列表">
                        <div v-for="(column, index) in currentDetail.columnConfigs" :key="index" class="config-detail">
                            <div class="config-item">
                                <span class="config-label">字段:</span>
                                <span class="config-value">{{ column.fieldCode }}</span>
                                <span class="config-label">列名:</span>
                                <span class="config-value">{{ column.headerText }}</span>
                                <span class="config-label">宽度:</span>
                                <span class="config-value">{{ column.widthPx }}px</span>
                                <span class="config-label">对齐:</span>
                                <span class="config-value">{{ getAlignText(column.align) }}</span>
                            </div>
                        </div>
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions v-if="currentDetail.filterConfigs && currentDetail.filterConfigs.length > 0"
                    title="筛选条件" :column="1" border class="mt-3">
                    <el-descriptions-item label="筛选条件列表">
                        <div v-for="(filter, index) in currentDetail.filterConfigs" :key="index" class="config-detail">
                            <div class="config-item">
                                <span class="config-label">字段:</span>
                                <span class="config-value">{{ filter.fieldCode }}</span>
                                <span class="config-label">运算符:</span>
                                <span class="config-value">{{ getSymbolText(filter.operator) }}</span>
                                <span class="config-label">值:</span>
                                <span class="config-value">{{ filter.valueText }}</span>
                            </div>
                        </div>
                    </el-descriptions-item>
                </el-descriptions>
            </div>

            <template #footer>
                <el-button @click="handleCloseViewDialog">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// API引入
import {
    getMonitoringList,
    getRefreshList,
    getAlignList,
    getSymbolList,
    getTableMonitorList,
    getTableMonitorDetail,
    addTableMonitor,
    updateTableMonitor,
    deleteTableMonitor
} from '@/api/dispatch/affair/tableSetting'

// 搜索表单
const searchForm = reactive({
    configCode: '',
    configName: '',
    targetType: '',
    refreshMode: '',
    isEnabled: ''
})

// 分页参数
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 下拉选项
const monitoringOptions = ref([])
const refreshOptions = ref([])
const alignOptions = ref([])
const symbolOptions = ref([])

// 字段选项
const fieldOptions = ref([
    { value: 'monitor_code', label: '监控编码' },
    { value: 'monitor_name', label: '监控名称' },
    { value: 'value', label: '数值' },
    { value: 'unit', label: '单位' },
    { value: 'status', label: '状态' },
    { value: 'update_time', label: '更新时间' },
    { value: 'location', label: '位置' },
    { value: 'department', label: '部门' }
])

// 表格数据
const tableData = ref([])
const selectedRows = ref([])
const loading = ref(false)
const submitting = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogType = ref('add') // add/edit
const activeTab = ref('basic')

// 当前详情
const currentDetail = ref(null)

// 预览数据
const previewData = ref([
    { monitor_code: 'M001', monitor_name: '水泵站1', value: '25.6', unit: 'MPa', status: '正常', update_time: '2025-11-09 10:30:00' },
    { monitor_code: 'M002', monitor_name: '水质监测点2', value: '7.2', unit: 'pH', status: '正常', update_time: '2025-11-09 10:25:00' },
    { monitor_code: 'M003', monitor_name: '管网压力点3', value: '0.8', unit: 'MPa', status: '警告', update_time: '2025-11-09 10:20:00' }
])

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
    id: '',
    configCode: '',
    configName: '',
    targetType: '',
    targetLabel: '',
    refreshMode: 1,
    refreshSeconds: 0,
    fontFamily: 'default',
    fontColor: '#000000',
    bgColor: '#ffffff',
    isEnabled: 1,
    remark: '',
    columnConfigs: [
        { fieldCode: 'monitor_code', headerText: '监控编码', widthPx: 120, align: 'left' },
        { fieldCode: 'monitor_name', headerText: '监控名称', widthPx: 150, align: 'left' },
        { fieldCode: 'value', headerText: '数值', widthPx: 100, align: 'right' },
        { fieldCode: 'unit', headerText: '单位', widthPx: 80, align: 'center' },
        { fieldCode: 'status', headerText: '状态', widthPx: 100, align: 'center' },
        { fieldCode: 'update_time', headerText: '更新时间', widthPx: 160, align: 'center' }
    ],
    filterConfigs: [
        { fieldCode: 'status', operator: '=', valueText: '正常' }
    ]
})

// 表单验证规则
const formRules = {
    configCode: [
        { required: true, message: '请输入配置编码', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    configName: [
        { required: true, message: '请输入配置名称', trigger: 'blur' },
        { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
    ],
    targetType: [
        { required: true, message: '请选择监控对象类型', trigger: 'change' }
    ],
    refreshMode: [
        { required: true, message: '请选择刷新模式', trigger: 'change' }
    ],
    refreshSeconds: [
        { required: true, message: '请输入刷新间隔', trigger: 'blur' },
        { type: 'number', min: 0, max: 3600, message: '刷新间隔在 0 到 3600 秒之间', trigger: 'blur' }
    ]
}

// 初始化数据
onMounted(() => {
    initData()
})

// 初始化数据
const initData = async () => {
    try {
        await Promise.all([
            fetchMonitoringList(),
            fetchRefreshList(),
            fetchAlignList(),
            fetchSymbolList()
        ])
        await fetchTableMonitorList()
    } catch (error) {
        console.error('初始化数据失败:', error)
        ElMessage.error('初始化数据失败')
    }
}

// 获取监控对象列表
const fetchMonitoringList = async () => {
    try {
        const res = await getMonitoringList()
        monitoringOptions.value = res.data || []
    } catch (error) {
        console.error('获取监控对象列表失败:', error)
        ElMessage.error('获取监控对象列表失败')
    }
}

// 获取刷新频率列表
const fetchRefreshList = async () => {
    try {
        const res = await getRefreshList()
        refreshOptions.value = res.data || []
    } catch (error) {
        console.error('获取刷新频率列表失败:', error)
        ElMessage.error('获取刷新频率列表失败')
    }
}

// 获取对齐方式列表
const fetchAlignList = async () => {
    try {
        const res = await getAlignList()
        alignOptions.value = res.data || []
    } catch (error) {
        console.error('获取对齐方式列表失败:', error)
        ElMessage.error('获取对齐方式列表失败')
    }
}

// 获取筛选符号列表
const fetchSymbolList = async () => {
    try {
        const res = await getSymbolList()
        symbolOptions.value = res.data || []
    } catch (error) {
        console.error('获取筛选符号列表失败:', error)
        ElMessage.error('获取筛选符号列表失败')
    }
}

// 获取表格监控配置列表
const fetchTableMonitorList = async () => {
    try {
        loading.value = true

        const params = {
            configCode: searchForm.configCode,
            configName: searchForm.configName,
            targetType: searchForm.targetType,
            refreshMode: searchForm.refreshMode,
            isEnabled: searchForm.isEnabled,
            pageNum: pagination.currentPage,
            pageSize: pagination.pageSize
        }

        const res = await getTableMonitorList(params)

        tableData.value = res.rows || []
        pagination.total = res.total || 0
    } catch (error) {
        console.error('获取表格监控配置列表失败:', error)
        ElMessage.error('获取表格监控配置列表失败')
    } finally {
        loading.value = false
    }
}

// 处理查询
const handleSearch = () => {
    pagination.currentPage = 1
    fetchTableMonitorList()
}

// 重置搜索
const resetSearch = () => {
    Object.assign(searchForm, {
        configCode: '',
        configName: '',
        targetType: '',
        refreshMode: '',
        isEnabled: ''
    })
    pagination.currentPage = 1
    handleSearch()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 新增配置
const handleAdd = () => {
    dialogType.value = 'add'
    resetForm()
    dialogVisible.value = true
}

// 查看详情
const handleView = async (row) => {
    try {
        const res = await getTableMonitorDetail(row.id)
        currentDetail.value = res.data
        viewDialogVisible.value = true
    } catch (error) {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败')
    }
}

// 编辑配置
const handleEdit = async (row) => {
    try {
        const res = await getTableMonitorDetail(row.id)
        dialogType.value = 'edit'
        Object.assign(formData, res.data)
        dialogVisible.value = true
    } catch (error) {
        console.error('获取编辑数据失败:', error)
        ElMessage.error('获取编辑数据失败')
    }
}

// 启用/停用
const handleToggleStatus = async (row, status) => {
    try {
        const actionText = status === 1 ? '启用' : '停用'
        await ElMessageBox.confirm(
            `确定要${actionText}该配置吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const updateData = { ...row, isEnabled: status }
        await updateTableMonitor(updateData)
        ElMessage.success(`${actionText}成功`)
        fetchTableMonitorList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('操作失败:', error)
            ElMessage.error('操作失败')
        }
    }
}

// 删除配置
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除该配置吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await deleteTableMonitor(row.id)
        ElMessage.success('删除成功')
        fetchTableMonitorList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的记录')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const ids = selectedRows.value.map(item => item.id).join(',')
        await deleteTableMonitor(ids)
        ElMessage.success('批量删除成功')
        selectedRows.value = []
        fetchTableMonitorList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }
}

// 批量启用
const handleBatchEnable = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要启用的记录')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要启用选中的 ${selectedRows.value.length} 条记录吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        for (const row of selectedRows.value) {
            const updateData = { ...row, isEnabled: 1 }
            await updateTableMonitor(updateData)
        }

        ElMessage.success('批量启用成功')
        selectedRows.value = []
        fetchTableMonitorList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量启用失败:', error)
            ElMessage.error('批量启用失败')
        }
    }
}

// 批量停用
const handleBatchDisable = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要停用的记录')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要停用选中的 ${selectedRows.value.length} 条记录吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        for (const row of selectedRows.value) {
            const updateData = { ...row, isEnabled: 0 }
            await updateTableMonitor(updateData)
        }

        ElMessage.success('批量停用成功')
        selectedRows.value = []
        fetchTableMonitorList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量停用失败:', error)
            ElMessage.error('批量停用失败')
        }
    }
}

// 添加列
const addColumn = () => {
    formData.columnConfigs.push({
        fieldCode: '',
        headerText: '',
        widthPx: 100,
        align: 'left'
    })
}

// 移除列
const removeColumn = (index) => {
    if (formData.columnConfigs.length > 1) {
        formData.columnConfigs.splice(index, 1)
    }
}

// 添加筛选条件
const addFilter = () => {
    formData.filterConfigs.push({
        fieldCode: '',
        operator: '',
        valueText: ''
    })
}

// 移除筛选条件
const removeFilter = (index) => {
    if (formData.filterConfigs.length > 1) {
        formData.filterConfigs.splice(index, 1)
    }
}

// 刷新预览
const refreshPreview = () => {
    ElMessage.success('预览已刷新')
}

// 重置表单
const resetForm = () => {
    Object.assign(formData, {
        id: '',
        configCode: '',
        configName: '',
        targetType: '',
        targetLabel: '',
        refreshMode: 1,
        refreshSeconds: 0,
        fontFamily: 'default',
        fontColor: '#000000',
        bgColor: '#ffffff',
        isEnabled: 1,
        remark: '',
        columnConfigs: [
            { fieldCode: 'monitor_code', headerText: '监控编码', widthPx: 120, align: 'left' },
            { fieldCode: 'monitor_name', headerText: '监控名称', widthPx: 150, align: 'left' },
            { fieldCode: 'value', headerText: '数值', widthPx: 100, align: 'right' },
            { fieldCode: 'unit', headerText: '单位', widthPx: 80, align: 'center' },
            { fieldCode: 'status', headerText: '状态', widthPx: 100, align: 'center' },
            { fieldCode: 'update_time', headerText: '更新时间', widthPx: 160, align: 'center' }
        ],
        filterConfigs: [
            { fieldCode: 'status', operator: '=', valueText: '正常' }
        ]
    })
    activeTab.value = 'basic'
    if (formRef.value) {
        formRef.value.clearValidate()
    }
}

// 关闭对话框
const handleCloseDialog = () => {
    dialogVisible.value = false
    resetForm()
}

// 关闭查看对话框
const handleCloseViewDialog = () => {
    viewDialogVisible.value = false
    currentDetail.value = null
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitting.value = true

        if (dialogType.value === 'add') {
            await addTableMonitor(formData)
            ElMessage.success('配置新增成功')
        } else {
            await updateTableMonitor(formData)
            ElMessage.success('配置更新成功')
        }

        dialogVisible.value = false
        fetchTableMonitorList()
    } catch (error) {
        console.error('提交失败:', error)
        if (error.errors) {
            return
        }
        ElMessage.error('操作失败')
    } finally {
        submitting.value = false
    }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    fetchTableMonitorList()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
    pagination.currentPage = page
    fetchTableMonitorList()
}

// 工具函数
const formatDateTime = (dateTimeString) => {
    if (!dateTimeString) return '-'
    try {
        return dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
    } catch {
        return dateTimeString
    }
}

const formatRefreshSeconds = (seconds, mode) => {
    if (mode === 1) return '实时'
    if (!seconds) return '-'
    if (seconds < 60) return `${seconds}秒`
    if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟`
    return `${Math.floor(seconds / 3600)}小时`
}

const getRefreshModeTag = (mode) => {
    switch (mode) {
        case 1: return 'success'
        case 2: return 'warning'
        default: return 'info'
    }
}

const getRefreshModeText = (mode) => {
    switch (mode) {
        case 1: return '实时'
        case 2: return '定时'
        default: return mode || '-'
    }
}

const getStatusTag = (status) => {
    switch (status) {
        case 1: return 'success'
        case 0: return 'danger'
        default: return 'info'
    }
}

const getStatusText = (status) => {
    switch (status) {
        case 1: return '启用'
        case 0: return '停用'
        default: return status || '-'
    }
}

const getAlignText = (align) => {
    switch (align) {
        case 'left': return '左对齐'
        case 'center': return '居中'
        case 'right': return '右对齐'
        default: return align || '-'
    }
}

const getSymbolText = (symbol) => {
    switch (symbol) {
        case '=': return '等于'
        case '!=': return '不等于'
        case '>': return '大于'
        case '>=': return '大于等于'
        case '<': return '小于'
        case '<=': return '小于等于'
        case 'like': return '包含'
        default: return symbol || '-'
    }
}

// 计算属性
const dialogTitle = computed(() => {
    return dialogType.value === 'add' ? '新增表格监控配置' : '编辑表格监控配置'
})
</script>

<style scoped lang="scss">
.search-card {
    margin-bottom: 20px;
}

.search-form {
    .el-row {
        margin-bottom: 0;
    }
}

.form-actions {
    text-align: left;
}

.table-card {
    margin-bottom: 20px;
}

.action-buttons {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.empty-table {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
}

.config-section {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 15px;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    font-weight: bold;
    font-size: 14px;
}

.config-list {
    max-height: 400px;
    overflow-y: auto;
}

.config-item {
    padding: 10px;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
    margin-bottom: 10px;
    background: #fafafa;
}

.config-detail {
    margin-bottom: 8px;
    padding: 8px;
    background: #f5f7fa;
    border-radius: 4px;
}

.config-item .config-item {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.config-label {
    font-weight: 500;
    color: #606266;
    font-size: 12px;
}

.config-value {
    color: #303133;
    font-size: 12px;
    margin-right: 15px;
}

.form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
}

.preview-section {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 15px;
}

.preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.preview-actions {
    display: flex;
    gap: 10px;
}

.preview-table {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    overflow: hidden;
}

:deep(.el-table) {
    .cell {
        white-space: nowrap;
        text-align: center;
    }

    th {
        text-align: center;
    }
}

:deep(.el-tabs) {
    .el-tabs__content {
        padding: 15px;
    }
}

:deep(.el-descriptions) {
    margin-bottom: 16px;
}

:deep(.el-descriptions__title) {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
}

:deep(.el-descriptions__label) {
    font-weight: 500;
    color: #606266;
}

:deep(.el-descriptions__content) {
    color: #303133;
}

:deep(.el-card) {
    margin-bottom: 20px;
}

:deep(.el-card):last-child {
    margin-bottom: 0;
}

.mt-2 {
    margin-top: 20px;
}

.mt-3 {
    margin-top: 16px;
}

@media (max-width: 768px) {
    .search-form .el-col {
        margin-bottom: 15px;
    }

    .action-buttons {
        flex-direction: column;
        align-items: stretch;
    }

    .config-item .el-col {
        margin-bottom: 10px;
    }
}
</style>